#include"DCLL.h"

DCLLNode* CreateDCLLNode(DCLLDataType x)
{
	DCLLNode* newnode = (DCLLNode*)malloc(sizeof(DCLLNode));
	if (newnode == NULL)
	{
		perror("malloc fail!");
		return NULL;
	}
	newnode->data = x;
	newnode->prev = NULL;
	newnode->next = NULL;
	return newnode;
}

DCLLNode* DCLLInit()
{
	DCLLNode* phead = CreateDCLLNode(-1);
	phead->prev = phead;
	phead->next = phead;
	return phead;
}

void DCLLPushBack(DCLLNode* phead, DCLLDataType x)
{
	assert(phead);
	DCLLNode* newnode = CreateDCLLNode(x);
	DCLLNode* tail = phead->prev;
	tail->next = newnode;
	newnode->prev = tail;
	phead->prev = newnode;
	newnode->next = phead;
}

void DCLLPrint(DCLLNode* phead)
{
	assert(phead);
	printf("<=head=>");
	DCLLNode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d<=>", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

bool DCLLisEmpty(DCLLNode* phead)
{
	assert(phead);
	return phead->next == phead;
}

void DCLLPopBack(DCLLNode* phead)
{
	assert(phead);
	assert(!DCLLisEmpty(phead));
	DCLLNode* tail = phead->prev;
	DCLLNode* tailPrev = tail->prev;
	tailPrev->next = phead;
	phead->prev = tailPrev;
	free(tail);
	tail = NULL;
}

void DCLLPushFront(DCLLNode* phead, DCLLDataType x)
{
	assert(phead);
	DCLLNode* newnode = CreateDCLLNode(x);
	DCLLNode* tmp = phead->next;
	phead->next = newnode;
	newnode->prev = phead;
	newnode->next = tmp;
	tmp->prev = newnode;
}

void DCLLPopFront(DCLLNode* phead)
{
	assert(phead);
	assert(!DCLLisEmpty(phead));
	DCLLNode* tmp = phead->next;
	DCLLNode* tmpnext = tmp->next;
	phead->next = tmpnext;
	tmpnext->prev = phead;
	free(tmp);
	tmp = NULL;
}

DCLLNode* DCLLFind(DCLLNode* phead, DCLLDataType x)
{
	assert(phead);
	DCLLNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void DCLLInsert(DCLLNode* pos, DCLLDataType x)
{
	assert(pos);
	DCLLNode* newnode = CreateDCLLNode(x);
	DCLLNode* prev = pos->prev;
	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;
}

void DCLLErase(DCLLNode* pos)
{
	assert(pos);
	DCLLNode* prev = pos->prev;
	DCLLNode* next = pos->next;
	prev->next = next;
	next->prev = prev;
	free(pos);
	pos = NULL;
}

void DCLLDestroy(DCLLNode* phead)
{
	assert(phead);
	DCLLNode* cur = phead->next;
	while (cur != phead)
	{
		DCLLNode* tmp = cur->next;
		free(cur);
		cur = tmp;
	}
	free(phead);
	phead = NULL;
}